import concurrent.futures
import glob
import logging
import os
from pathlib import Path

import pytest
from tools.decorators import log_decorator
from tools.login聚水潭 import login_聚水潭
from tools.page import page_get_no
from tools.上传至erp import 上传ERP
from tools.合并excel import merge_excel_files
from tools.获取物流轨迹 import 获取物流轨迹及具体原因


@pytest.mark.run(order=2)
@log_decorator
def 获取物流轨迹_test(username, date):
    page = page_get_no()
    login_聚水潭(['15867710780', 'yexiong1997'], page)
    tab = page.new_tab('https://www.erp321.com/epaas')
    tab1 = page.new_tab('https://www.erp321.com/epaas')
    tab2 = page.new_tab('https://www.erp321.com/epaas')
    dfs = username
    for df in dfs:
        logging.info('创建线程池')
        with concurrent.futures.ThreadPoolExecutor() as executor:
            try:
                if df.iloc[0]['店铺名称']:
                    executor.submit(获取物流轨迹及具体原因, page,
                                    f"C:\\投诉模板\\{date}\\{df.iloc[0]['店铺名称']}.xlsx")
                if df.iloc[1]['店铺名称']:
                    executor.submit(获取物流轨迹及具体原因, tab, f"C:\\投诉模板\\{date}\\{df.iloc[1]['店铺名称']}.xlsx")
                if df.iloc[2]['店铺名称']:
                    executor.submit(获取物流轨迹及具体原因, tab1,
                                    f"C:\\投诉模板\\{date}\\{df.iloc[2]['店铺名称']}.xlsx")
                if df.iloc[3]['店铺名称']:
                    executor.submit(获取物流轨迹及具体原因, tab2,
                                    f"C:\\投诉模板\\{date}\\{df.iloc[3]['店铺名称']}.xlsx")
            except Exception as e:
                break
            finally:
                executor.shutdown(True)
    logging.info('所有线程执行完毕')
    page.quit()
    file_path = f"C:\\投诉模板\\{date}"
    output_file = f"C:\\投诉模板\\{date}\\投诉模板.xlsx"
    if Path(output_file).exists():
        Path(output_file).unlink()
    logging.info('开始合并Excel')
    input_files = glob.glob(os.path.join(file_path, "*.xlsx"))
    merge_excel_files(input_files, output_file)
    logging.info('合并Excel成功')
    上传ERP(output_file)
